﻿using ConfExpert.Utility;
using ConfExpert.Utility.Ribbon;
using ConfOrderDS;
using DevExpress.XtraEditors;
using DevExpress.XtraSplashScreen;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;


namespace ConfOrder
{
    public partial class MainForm : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        int WhoAmI = AppSession.UserInfo.UserId;
        System.Timers.Timer timer = null;
        DateTime alertTime1 = new DateTime(2000, 1, 1);
        Dictionary<string, XForm> forms = new Dictionary<string, XForm>();

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            AppSession appSession = new AppSession("ConfOrder");
            ribbon.ForceInitialize();
            this.Text = "ConfOrder" + (AppSession.Version != null ? " - v" + AppSession.Version : "");


            bsiUser.Caption = ConfExpert.Utility.AppSession.UserInfo.UserName + " / " + ConfExpert.Utility.AppSession.DatabaseName;

            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(AppSession.Settings.SkinName);
            this.AllowFormGlass = AppSession.Settings.AllowFormGlass;

            InitializeTimer();

            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(MainForm_FormClosing);

            this.KeyDown += new KeyEventHandler(MainForm_KeyDown);

            this.MdiChildActivate += new System.EventHandler(this.MainForm_MdiChildActivate);

            InitializeRibbon();
            this.WindowState = FormWindowState.Maximized;

            RepositoryManager.dsi.COStyle.Clear();
            AppSession.DataManager.Fill(RepositoryManager.dsi, "COStyle", "COGetStyles", AppSession.UserInfo.CustomerId);
            RepositoryManager.dsi.COOrderRef.Clear();
            AppSession.DataManager.Fill(RepositoryManager.dsi, "COOrderRef", "COGetOrderRef", AppSession.UserInfo.CustomerId);


            SplashScreenManager.CloseForm();
        }

        private void InitializeTimer()
        {
            timer = new System.Timers.Timer(60000);    //once a minute!
            timer.SynchronizingObject = this;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(RaiseUpdate);
            timer.Enabled = true;

            bwRefreshLk.DoWork += new System.ComponentModel.DoWorkEventHandler(backgroundWorker1_DoWork);
            bwRefreshLk.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
        }

        private void InitializeRibbon()
        {
            RibbonManager rm = new RibbonManager(Ribbon);
            rm.Init();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                DateTime FeaMod = new DateTime(2000, 1, 1);

                RepositoryManager.dsi.Settings.Clear();
                RepositoryManager.dsi.Merge(e.Result as AppDS);
                RepositoryManager.RemoveDeletedRows();

                if (DateTime.UtcNow.Subtract(alertTime1).TotalSeconds > 590)
                    if (AppSession.Version != null)
                        if (RepositoryManager.dsi.Settings.FindByName("PublishVersion").Val.CompareTo(AppSession.Version) > 0)
                        {
                            alertPopup.Show(this, "There is a newer version! " + RepositoryManager.dsi.Settings.FindByName("PublishVersion").Val,
                                "\nPlease save your works and restart the program.");

                            alertTime1 = DateTime.UtcNow;
                        }
            }
        }

        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            e.Result = AppSession.RepositoryManager.RefreshData(RepositoryManager.GetLastModified());
        }

        private void RaiseUpdate(object sender, System.Timers.ElapsedEventArgs e)
        {
            timer.Enabled = false;
            RefreshData();
            timer.Enabled = true;
        }

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (Environment.MachineName == "KGULCAN")
            {
                if (e.Control && e.KeyCode == Keys.F12)
                {
                    RibbonManager rm = new RibbonManager(Ribbon);
                    rm.Init();
                }
            }
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            AppSession.MainForm.ShowInTaskbar = true;
            AppSession.DataManager.ExecuteNonQuery("UpdLogPrg", AppSession.UserInfo.UserId, AppSession.Version, 0, 0, 0);
        }

        private void MainForm_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            PersistDsi();
        }

        private void PersistDsi()
        {
            try
            {
                string connstr = "Data Source=" + AppSession.sqlitefile + "; PRAGMA synchronous=off; PRAGMA journal_mode = MEMORY";

                bool yaz = true;
                if (File.Exists(AppSession.sqlitefile))
                {
                    FileInfo fi = new FileInfo(AppSession.sqlitefile);
                    if ((DateTime.Today - fi.LastWriteTime.Date).TotalDays < 3)
                        yaz = false;
                }

                if (yaz)
                {
                    this.Cursor = Cursors.WaitCursor;

                    SplashScreenManager.ShowForm(typeof(SplashSaving));

                    if (!File.Exists(AppSession.sqlitefile))
                        SQLiteConnection.CreateFile(AppSession.sqlitefile);

                    using (var con = new SQLiteConnection(connstr))
                    using (var cmd = new SQLiteCommand(con))
                    {
                        con.Open();
                        cmd.CommandText = @"    DROP TABLE IF EXISTS V_Kumas;
                                                CREATE TABLE [V_Kumas]( [ProductId] int PRIMARY KEY NOT NULL, [PhotoMikro] [BLOB], [Name] [varchar](500), [KVendorId] [int], [KCustomerId] [int], [KompozisyonId] [int], [FinishId] [int], [Konstruksiyon] [varchar](500), [KaliteId] [int], [KaliteAciklama] [varchar](500), [Desc7C] [varchar](500), [DescK] [varchar](500), [FabricTypeId] [int], [EnGrubu] [varchar](50), [DesenYonuId] [int], [DesenId] [int], [OrguId] [int], [Agirlik] [varchar](50), [Grup7CId] [int], [GrupESPId] [int], [Tags] [varchar](500), [RaporBoyuId] [int], [YTalimatId] [int], [Notes] [varchar](500), [CheckedOn] [datetime], [ModifiedOn] [datetime], [Hue] [real], [UserId] [int], [Deleted] [bit], [TS] [varbinary]);

                                                DROP TABLE IF EXISTS V_Aksesuar;
                                                CREATE TABLE [V_Aksesuar]( [AksesuarId] [int], [PhotoMikro] [BLOB], [StokKod] [varchar](250), [AksSeriId] [int], [BrandId] [int], [ProductCategoryId] [int], [Etiket] [varchar](300), [Renk] [varchar](50), [Boy] [varchar](50), [Aciklama] [varchar](300), [ModifiedOn] [datetime], [TS] [varbinary], [Deleted] [bit])";
                        cmd.ExecuteNonQuery();
                    }

                    Upd("V_Kumas", RepositoryManager.dsi.V_Kumas.CopyToDataTable(), connstr);
                    Upd("V_Aksesuar", RepositoryManager.dsi.V_Aksesuar.CopyToDataTable(), connstr);

                    SplashScreenManager.CloseDefaultSplashScreen();

                    this.Cursor = Cursors.Default;
                }
            }
            catch
            {
            }
        }


        private static void Upd(string tablename, DataTable dt, string connstr)
        {
            using (var con = new SQLiteConnection(connstr))
            {
                con.Open();
                using (SQLiteTransaction tr = con.BeginTransaction())
                using (var adapter = new SQLiteDataAdapter("SELECT * FROM " + tablename, con))
                {
                    using (adapter.InsertCommand = new SQLiteCommandBuilder(adapter).GetInsertCommand())
                    {
                        adapter.InsertCommand.Transaction = tr;
                        foreach (DataRow row in dt.Rows)
                            row.SetAdded();

                        var sw = Stopwatch.StartNew();
                        int numRowsUpdated = adapter.Update(dt);
                        sw.Stop();
                        double t2 = sw.Elapsed.TotalMilliseconds;
                        tr.Commit();
                    }
                }
            }
        }

        private void MainForm_MdiChildActivate(object sender, EventArgs e)
        {
            XForm frm = (XForm)this.ActiveMdiChild;
            NotifySelectionInfo(frm);
        }

        public XForm ShowMdiChildForm(Type type, params object[] prm)
        {
            XForm frm = null;

            forms.TryGetValue(type.GetHashCode() + "." + prm.GetHashCode(), out frm);

            if (frm != null)
                if (!frm.IsDisposed)
                {
                    AppSession.DataManager.ExecuteNonQuery("InsLogForm", WhoAmI, frm.GetType().ToString());
                    frm.Activate();
                    return frm;
                }
                else
                    forms.Remove(type.GetHashCode() + "." + prm.GetHashCode());

            try
            {
                if (type.BaseType == typeof(XPopupForm))
                {
                    using (XPopupForm popup = (XPopupForm)Activator.CreateInstance(type, prm))
                    {
                        AppSession.DataManager.ExecuteNonQuery("InsLogForm", WhoAmI, popup.GetType().ToString());
                        popup.ShowDialog();
                    }
                }
                else
                {
                    frm = (XForm)Activator.CreateInstance(type, prm);
                    frm.MdiParent = this;
                    frm.WindowState = FormWindowState.Maximized;
                    forms.Add(type.GetHashCode() + "." + prm.GetHashCode(), frm);
                    AppSession.DataManager.ExecuteNonQuery("InsLogForm", WhoAmI, frm.GetType().ToString());
                    frm.Show();
                }
            }
            catch (Exception Ex)
            {
                XtraMessageBox.Show(Ex.InnerException.ToString());
            }
            finally
            {

            }

            return frm;
        }

        public void NotifySelectionInfo(XForm frm)
        {
            if (frm != null && !frm.IsDisposed)
                bsiCustomSelectionInfo.Caption = frm.SelectionInfo;
        }

        public void RefreshData()
        {
            if (!bwRefreshLk.IsBusy)
                bwRefreshLk.RunWorkerAsync();
        }


        public void NotifyMain(string message)
        {
            bsiInfo.Caption = DateTime.Now.ToLongTimeString() + " | " + message;
        }



    }
}